<?php

namespace app\admin\controller\workteam;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Date;
use fast\Tree;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;


/**
 * 任务管理
 */
class Task extends Backend
{

    protected $noNeedRight = ['info'];
	protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new  \app\admin\model\workteam\Task();
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("levelList", $this->model->getLevelList());
    }

    /**
     * 查看列表
     */
    public function index()
    {

        $scene = model('\app\admin\model\workteam\Scene');
        $scene_list = $scene->where('types', 'task')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->order('weigh asc,id asc')->column('id,name');

        if ($this->request->isAjax()) {
            $filter_w = $this->getFilterWhere($scene_list);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
//                $this->request->request(['custom' => $filter_w]);		// selectpage报错所以注释掉
                return parent::selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->fetchSql(false)
                ->count();

            //任务排序方法，如果是id,把重要的，将要过期的，未完成的任务排序在前面
            if ($sort==''){
                $this->model->orderRaw("field(status,'0','1','2') ,level desc,id desc");
            }else{
                $this->model->order($sort, $order);
            }

            $list = $this->model
                ->where($where)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                },
                    'project' => function ($q) {
                        $q->field('id,name,status');
                    }])
                ->where($filter_w)
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->assignconfig("levelList", $this->model->getLevelList());
        $this->assignconfig("scene_list", $scene_list);
        $this->view->assign("scene_list", $scene_list);
        return $this->view->fetch();

    }

    /**
     * 子任务列表
     * @param null $ids
     */
    public function childList($ids = null)
    {

        if (!$ids) $this->error(__("请求有误"));

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\workteam\library\Auth();

        if (!$auth->taskAuth($row, $this->auth)) {
            $this->error(__('您没有权限查阅任务'));
        }


        if ($this->request->isAjax()) {
            $filter_w = [];
            $filter_w['pid'] = $ids;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return parent::selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                }])
                ->where($filter_w)
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->error(__("请求有误"));
    }

    /**
     * 添加主任务
     * @param null $ids 项目ID
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add($ids = null)
    {

        $params = $this->request->post("row/a");
        $ids = isset($params['project_id']) ? $params['project_id'] : $ids;


        if ($this->request->isPost()) {

            if (!$ids) {
                $this->error(__("项目不能为空"));
            }
            //如果有项目ID，就判断当前项目是否之可以添加任务的状态[0,1]
            $projectModel = new  \app\admin\model\workteam\Project();
            $prow=$projectModel->where('id', $ids)->where('status', 'in', ['0', '1'])->find();
            if (!$prow) {
                $this->error(__("不能添加任务:当前项目状态不正常"));
            }
            //判断是否有权限
            $auth = new \addons\workteam\library\Auth();
            if (!$auth->projectAuth($prow, $this->auth)) {
                $this->error(__('项目相关人员才能添加主任务'));
            }

            if ($params) {
                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : time();
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : time();
				if(!isset($params['alert_minute']) || $params['alert_minute'] == 0){
					$params['alert_time_auto'] = $params['start_time'] - time();
					$params['alert_time'] = 0;
					$params['alert_minute'] = 0;
				}else{
					$params['alert_time'] = $params['alert_minute'] * 60;
					$params['alert_time_auto'] = 0;
				}
                $params = array_merge($params, [
                    'create_admin_id' => $this->auth->id,
                ]);

				$cycle = $this->request->post('cycle');

				$this->model->startTrans();
				try{
					$dates = $this->getDatesByCycle($cycle, $params['start_time'], $params['end_time']);
					if($dates == false){
						$result = $this->model->add($params['project_id'], $params);
					}else{
						$now = time();
						$task_id = 0;
						$task_name = $params['name'];
						foreach($dates as $k=>$v){
							if($cycle == 4) $params['name'] = $task_name.'.d'.$v['day'];
							$params['start_time'] = $v['start_time'];
							$params['end_time'] = $v['end_time'];
							$params['alert_time_auto'] = $v['start_time'] - $now;
							$params['cycle_id'] = $task_id;
//							$params['plan_hours'] = 0;		// 避免工时不足的问题
							$taskModel = new \app\admin\model\workteam\Task();
							$result = $taskModel->add($params['project_id'], $params, [], $cycle, $task_id);
							if(!$result) break;
							if($task_id == 0){
								$task_id = $taskModel->id;
							}
						}
					}
					if (!$result){
						$this->model->rollback();
						$error_msg = $dates ? $taskModel->getError() : $this->model->getError();
						$this->error($error_msg);
					}
					$this->model->commit();
                	$this->success();
				}catch (Exception $e){
					$this->model->rollback();
					$error_msg = $e->getMessage();
					if(config('app_debug')) $error_msg.= ' in '.$e->getFile().' line '.$e->getLine();
					$this->error($error_msg);
				}
            }
            $this->error(__('Parameter %s can not be empty', ''));


        }
        $this->getGroupdata();
		$this->assign('month_days',$this->getMonthDays());
        return $this->view->fetch();
    }

	protected function getDatesByCycle($cycle_type, $from_time, $to_time){
		switch ($cycle_type){
			case 1:
			case 4:
				$start_time = $this->request->post('day_start_time');
				$end_time = $this->request->post('day_end_time');
				break;
			case 2:
				$start_time = $this->request->post('week_start_time');
				$end_time = $this->request->post('week_end_time');
				break;
			case 3:
				$start_time = $this->request->post('month_start_time');
				$end_time = $this->request->post('month_end_time');
				break;
		}
		if($cycle_type!=0){
			$dates = [];
			$from_time = $from_time >= time() ? $from_time : time();
			if($cycle_type == 4) $to_time = $from_time + 30 * 24 * 3600;
			$i = -1;
			while(true){
				$i++;
				$starttime = strtotime(date('Y-m-d '.$start_time, $from_time).' +'.$i.' day');
				$endtime = strtotime(date('Y-m-d '.$end_time, $from_time).' +'.$i.' day');
				if($starttime <= $to_time){
					if($cycle_type == 2){
						$cycle_week = $this->request->post('cycle_week/a');
						if(!in_array(date('N', $starttime),$cycle_week)) continue;
					}elseif($cycle_type == 3){
						$cycle_month = $this->request->post('cycle_month/a');
						$month_last_day = date('j', strtotime(date('Y-m',$starttime).' last day of this month'));
//						if(date('j', $starttime) != $cycle_month && !(date('j', $starttime) == $month_last_day && $cycle_month > $month_last_day)) continue;
						if(!in_array(date('j', $starttime),$cycle_month)) continue;
					}elseif($cycle_type == 4){
						//艾宾浩斯遗忘曲线:0天，1天，1周，1月
//						if(!in_array($i,[0,1,7,30])) continue;
						if(!in_array($i,[0,1,3,7,15,30])) continue;
					}
					$dates[] = ['day' => $i, 'start_time' => $starttime, 'end_time' => $endtime];
				}else{
					break;
				}
			}
		}else{
			$dates = false;
		}
		return $dates;
	}

    /**
     * 修改
     * @param null $ids
     * @return mixed
     */
    public function edit($ids = null)
    {


        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\workteam\library\Auth();

        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('您没有权限操作任务'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //已经完成的任务不能再修改
                if ($row->status==2){
//                    $this->error(__('已经完成的任务不能再修改'));
					$params['status'] = 2;
                }

                if ($params['status']==2 && $row->status!=2) {
                    if (!isset($params['complete_time']) || $params['complete_time'] <= 0) {
                        $this->error(__("请输入完成时间"));
                    }
                    $params['complete_time'] = strtotime($params['complete_time']);
					$logData = [
						'customer_id' => $row->project->customer_id,
						'project_id' => $row->project_id,
						'task_id' => $row->id,
						'service_client' => $params['service_client'],
						'service_time' => $params['complete_time'],
						'content' => $params['content'],
						'secret' => $params['secret'],
						'create_user_id' => $this->auth->id,
					];
                    if (!$row->complete($logData, $params['complete_time'])){
                        $this->error($row->getError());
                    }
                }


                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : time();
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : time();
                if (isset($params['complete_time'])) {
                    $params['complete_time'] = isset($params['complete_time']) && $params['complete_time'] ? strtotime($params['complete_time']) : time();
                }
				if(!isset($params['alert_minute']) || $params['alert_minute'] == 0){
					$params['alert_time_auto'] = $params['start_time'] - time();
					$params['alert_time'] = 0;
					$params['alert_minute'] = 0;
				}else{
					$params['alert_time'] = $params['alert_minute'] * 60;
					$params['alert_time_auto'] = 0;
				}
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);

					// 重新计算获得工时
					$params['get_hours'] = $this->model->getParentTaskGetHours($row->id, $params['plan_hours'], 0);
					if($params['get_hours'] < 0){
						Db::rollback();
						$this->error('任务安排工时不足，请调整子任务工时');
					}

                    $result = $row->allowField(true)->save($params);

					// 上级任务工时
					if($row->ptask){
						$ptask_get_hours = $this->model->getParentTaskGetHours($row->ptask->id, $row->ptask->plan_hours, $params['plan_hours'], $row->id);
						if($ptask_get_hours < 0){
							Db::rollback();
							$this->error('父任务安排工时不足');
						}
						$row->ptask->get_hours = $ptask_get_hours;
						$row->ptask->save();
					}

					// 项目工时
					if($row->pid == 0){
						$project_task_hours = $this->model->getProjectTaskHours($row->project->id, $params['plan_hours'], $row->id);
						if($project_task_hours > $row->project->plan_hours){
							Db::rollback();
							$this->error('项目工时不足');
						}
						$row->project->task_hours = $project_task_hours;
					}
					$row->project->actual_hours = $this->model->getProjectActualHours($row->project->id, $row->get_hours, $row->id);
					$row->project->save();

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->getGroupdata();
        $this->view->assign("row", $row);

		$facrm_config = get_addon_config('facrm');
		$this->view->assign("service_client", $facrm_config['service_client']);
        return $this->view->fetch();

    }

    /**
     * 子任务
     * @param null $ids
     */
    public function addchild($ids = null)
    {
        if (!$ids)
            $this->error(__('父任务不存在'));

        $parent_task = $this->model->with(['project'])->find($ids);
        if (!$parent_task)
            $this->error(__('父任务不存在'));
        if (!$parent_task->project)
            $this->error(__("项目不存在"));
        //如果项目不是未开始和进行中的，都不给添加任务
        if (!in_array($parent_task->project->status, [1, 0]))
            $this->error(__("项目是不可添加任务状态"));

        if (!in_array($parent_task->status, [1, 0]))
            $this->error(__("父任务是不可添加子任务状态"));

        $auth = new \addons\workteam\library\Auth();

        if (!$auth->edTaskAuth($parent_task, $this->auth)) {
            $this->error(__('您没有权限添加子任务'));
        }


        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : time();
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : time();
                $params = array_merge($params, [
                    'create_admin_id' => $this->auth->id,
                    'pid' => $parent_task->id,
                ]);

				$cycle = $this->request->post('cycle');

				$this->model->startTrans();
				try{
					$dates = $this->getDatesByCycle($cycle, $params['start_time'], $params['end_time']);
					if($dates == false){
						$result = $this->model->addchild($parent_task, $params);
					}else{
						$now = time();
						$task_id = 0;
						$task_name = $params['name'];
						foreach($dates as $k=>$v){
							if($cycle == 4) $params['name'] = $task_name.'.d'.$v['day'];
							$params['start_time'] = $v['start_time'];
							$params['end_time'] = $v['end_time'];
							$params['alert_time_auto'] = $v['start_time'] - $now;
							$params['cycle_id'] = $task_id;
//							$params['plan_hours'] = 0;		// 避免工时不足的问题
							$taskModel = new \app\admin\model\workteam\Task();
							$result = $taskModel->addchild($parent_task, $params, [], $cycle, $task_id);
							if(!$result) break;
							if($task_id == 0){
								$task_id = $taskModel->id;
							}
						}
					}
					if (!$result){
						$this->model->rollback();
						$error_msg = $dates ? $taskModel->getError() : $this->model->getError();
						$this->error($error_msg);
					}
					$this->model->commit();
                	$this->success();
				}catch (Exception $e){
					$this->model->rollback();
					$error_msg = $e->getMessage();
					if(config('app_debug')) $error_msg.= ' in '.$e->getFile().' line '.$e->getLine();
					$this->error($error_msg);
				}
            }
            $this->error(__('Parameter %s can not be empty', ''));


        }

        $this->view->assign("row", $parent_task);
        $this->getGroupdata();
		$this->assign('month_days',$this->getMonthDays());
        return $this->view->fetch();
    }

    /**
     * 任务开始
     */
    public function start($ids = null)
    {
        $progress = $this->request->request('progress', '', 'intval');//进度

        if (!$ids)
            $this->error(__('父任务不存在'));

        $row = $this->model->with(['project'])->find($ids);

        if (!$row)
            $this->error(__('任务不存在'));
        if (!$row->project)
            $this->error(__("项目不存在"));
        //如果项目不是未开始和进行中的，都不给添加任务
        if (!in_array($row->project->status, [1, 0]))
            $this->error(__("项目状态不正常"));


        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row,$this->auth)) {
            $this->error(__('您没有权限操作任务'));
        }

        if (!in_array($row->status, [1, 0]))
            $this->error(__("任务状态不正常"));
        if ($row->project->status == 0) {
            $row->project->status = 1;//项目设置为进行中
            $row->project->save();
        }

        if ($progress != $row->progress ) {
            if ($progress < 0 || $progress > 100)
                $this->error(__("进度只能是0~100"));
            \app\admin\model\workteam\Log::setTitle(__('修改任务进度'));
            $row->progress = $progress;
        }else{
            \app\admin\model\workteam\Log::setTitle(__('开始任务'));
        }
        $row->status = 1;

        $row->save();
        $this->success();
    }

    /**
     * 完成任务
     * @param null $ids
     */
    public function complete($ids = null)
    {


        if (!$ids)
            $this->error(__('任务不存在'));

        $row = $this->model->with(['project'])->find($ids);
        if (!$row)
            $this->error(__('任务不存在'));
        if (!$row->project)
            $this->error(__("项目不存在"));

        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('任务负责人才有权限修改'));
        }

		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			$logData = [
				'customer_id' => $row->project->customer_id,
				'project_id' => $row->project_id,
				'task_id' => $row->id,
				'service_client' => $params['service_client'],
				'service_time' => $params['service_time'],
				'service_hours' => $params['service_hours'],
				'content' => $params['content'],
				'secret' => $params['secret'],
				'create_user_id' => $this->auth->id,
			];
			if (!$row->complete($logData)){
				$this->error($row->getError());
			}
			$this->success();
		}

		$facrm_config = get_addon_config('facrm');
		$this->view->assign("service_client", $facrm_config['service_client']);
		$this->view->assign("row",$row);
		return $this->view->fetch();
    }

    /**
     * 反完成
     * @param null $ids
     */
    public function ucomplete($ids = null){
        //把完成的任务标记为不完成状态
        if (!$ids)
            $this->error(__('任务不存在'));

        $row = $this->model->with(['project'])->find($ids);
        if (!$row)
            $this->error(__('任务不存在'));
        if (!$row->project)
            $this->error(__("项目不存在"));

        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('任务负责人才有权限修改'));
        }

        if (!$row->ucomplete()){
            $this->error($row->getError());
        }
        $this->success();

    }


    /**
     * 获取任务信息【不需要权限的】
     * @internal
     */
    public function info($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->success('', '', $row);
    }

    /**
     * 获取全部组
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getGroupdata()
    {
        $auth = new \addons\workteam\library\Auth();
        $groupdata=$auth->getAllDepartmentsTreeArray($this->auth->id);
        $groupdata[0] = '选择归属部门';

        $departmentIds=$auth->getDepartmentIds($this->auth);
        $this->view->assign('groupdata', $groupdata);
        $this->view->assign('departmentIds', $departmentIds);

    }


    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 12;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            $auth = new \addons\workteam\library\Auth();
            switch ($filter['scene_id']) {
                case 1:
                    //全部
                    $childrenAdminIds = $auth->childrenAdminIds($this->auth,true);
                    $admin_id = $this->auth->id;
                    $filter_w[] = function ($query) use ($admin_id, $childrenAdminIds) {
                        $query->whereOr('admin_id',$admin_id)->whereOr('admin_id', 'in', $childrenAdminIds)->whereOr([Db::raw("FIND_IN_SET(" . $admin_id . ",admin_ids)")]);
                    };

                    break;
                case 2:
                    //我的
                    $filter_w['admin_id'] = $this->auth->id;
                    break;
                case 3:
                    //下属
                    $this->childrenAdminIds = $auth->childrenAdminIds($this->auth,false);
                    if ($this->childrenAdminIds){
                        $filter_w['admin_id'] = ['in', $this->childrenAdminIds];
                    }else{
                        $filter_w['admin_id'] ='-1';
                    }

                    break;
                case 4:
                    //参与
                    $admin_id = $this->auth->id;
                    $filter_w[] = function ($query) use ($admin_id) {
                        $query->where([Db::raw("FIND_IN_SET(" . $admin_id . ",admin_ids)")]);
                    };
                    break;
				case 12:
                    $admin_id = $this->auth->id;
					$filter_w[] = function ($query) use ($admin_id){
                        $query->where('admin_id',$admin_id)->whereTime('start_time','between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]);
                    };
					break;
				default://其它的还做TODO
                    $filter_w['admin_id'] = $this->auth->id;
			}
            if (isset($filter['expire_type'])) {
                $this->expire_type = $filter['expire_type'];
                unset($filter['expire_type']);
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }

		if($this->request->param('project_id',0)){
			$filter_w['project_id'] = $this->request->param('project_id');
		}
        return $filter_w;
    }

    /**
     * 任务详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->taskAuth($row, $this->auth)) {
            $this->error(__('您没有权限查看任务'));
        }

        $this->view->assign("row", $row);
		$logModel = new \app\admin\model\workteam\Log();
		$this->assignconfig('createTypeList', $logModel->getCreateTypeList());
		$this->view->assign('typeList', $logModel->getTypeList());
        $this->assignconfig("statusList", $this->model->getStatusList());
        return $this->view->fetch();
    }


    /**
     * 附件
     */
    public function fileslist($task_id = null)
    {
        if (!$task_id) {
            $this->error(__("任务不存在"));
        }
        $row = $this->model->get($task_id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //判断是否有权限查看
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->taskAuth($task_id, $this->auth)) {
            $this->error(__('任务负责人员才有权限查看'));
        }

        $this->model = new \app\admin\model\workteam\Files();

        if ($this->request->isAjax()) {
            $filter_w = [];
            $filter_w['task_id'] = $task_id;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                $this->request->request(['custom' => $filter_w]);
                return parent::selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                }
                ])

                ->where($filter_w)
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();

            foreach ($list as $k => &$row) {
                $row['fullurl'] = cdnurl($row['url'], true);
                $row['imagetype'] = pathinfo($row['url'], PATHINFO_EXTENSION);
            }


            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 附件上传
     */
    public function filesadd($task_id = null)
    {
        $url = $this->request->param('url');
        if (!$url || !$task_id) $this->error(__("参数不完整"));

        $row = $this->model->with(['project'])->find($task_id);
        if (!$row) $this->error(__("任务不存在"));

        if (!$row->project)
            $this->error(__("项目不存在"));
        //如果项目不是未开始和进行中的，都不给添加任务
        if (!in_array($row->project->status, [1, 0]))
            $this->error(__("项目状态不正常"));

        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('任务人员才有权限操作'));
        }
        //获取附件名称
        $attachment= \app\common\model\Attachment::where('url',$url)->find();

        $files_data = array();
        $files_data['url'] = $url;
        $files_data['admin_id'] = $this->auth->id;
        $files_data['project_id'] = $row->project->id;
        $files_data['task_id'] = $task_id;
        $files_data['create_time'] = time();
        $files_data['filename'] = isset($attachment['filename'])?$attachment['filename']:$url;
        $row->files()->save($files_data);
        $this->success();
    }

    /**
     * 删除附件
     * @param string $ids
     */
    public function filesdel($ids = "")
    {

        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        if ($ids) {
            $this->model = new \app\admin\model\workteam\Files();
            $info = $this->model->where('id', $ids)->find();
            if (!$info) $this->error(__("记录不存在"));

            //判断是否有权限
            $auth = new \addons\workteam\library\Auth();
            if (!$auth->edTaskAuth($info['task_id'], $this->auth)) {
                $this->error(__('任务人员才有权限操作'));
            }

            $count = 0;
            Db::startTrans();
            try {
                $info->delete();
                $count++;
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));

        parent::del();
    }

    /**
     * 添加任务动态
     * @param string $ids 任务ID
     */
    public function addlog($ids = ""){


        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        //判断是否有权限修改
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('您没有权限操作任务'));
        }

        //如果项目不是未开始和进行中的，都不给添加
        if (!in_array($row->project->status, [1, 0]))
            $this->error(__("项目状态不正常"));

        $this->model = new  \app\admin\model\workteam\Log();


        if ($this->request->isPost()){

            $params = $this->request->post("row/a");
            if (!$params) $this->error(__("提交参数有误"));

            if (!isset($params['title'])||!$params['title']){
                $this->error(__("请输入标题"));
            }
            if (!isset($params['content'])||!$params['content']){
                $this->error(__("请输入内容"));
            }

            if (isset($params['notice'])&&!$params['admin_ids']){
                $this->error(__("请选择通知人员"));
            }

            $result = false;
            Db::startTrans();
            try {
                $result= \app\admin\model\workteam\Log::record($row->project_id ,$row->id, $params['title'],$params['content'],isset($params['type'])?$params['type']:0,1, $params['service_client']);
                if ($result&&isset($params['notice'])){
                    //消息通知
					$params['link'] = config('admin.crm_url').url('workteam/log/detail',['ids'=>$result->id]);
                    $params['key']='notice_task_log';
                    $params=array_merge($row->project->toArray(),$params);
                    Queue::push('addons\workteam\library\notice\queue\TaskJob',$params);
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();

        }
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign([
            'row'=>$row
        ]);
		$facrm_config = get_addon_config('facrm');
		$this->view->assign("service_client", $facrm_config['service_client']);
        return $this->view->fetch();
    }

    /**
     * 删除
     * @param string $ids
     *
     */
    public function del($ids = "")
    {
        //已经完成的不能删除，有子任务的不能删除
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        if (!$ids)
            $this->error(__('任务不存在'));

        $row = $this->model->with(['project'])->find($ids);
        if (!$row)
            $this->error(__('任务不存在'));
        if (!$row->project)
            $this->error(__("项目不存在"));

        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edTaskAuth($row, $this->auth)) {
            $this->error(__('任务负责人才有权限删除'));
        }


        //如果项目是完成和归档的，不给删除
        if (in_array($row->project->status,[2,3])) {
            $this->error(__('该任务属于完成或归档项目，不能删除')) ;
        }

        //如果有子任务不给删除
        if ($this->model->where('pid',$ids)->count()){
            $this->error (__('该任务有子任务，请先删除子任务'));
        }

        Db::startTrans();
        try {
            if ($row->status==2) {//如果是完成的任务也要减去相关数据
                //项目完成任务数量-1
                $row->project->task_complate--;
                //减去项目完成工时
                $row->project->actual_hours= $row->project->actual_hours-$row->get_hours;
            }

            //如果是子任务，就归还可得工时给上级
            if ($row->pid){
                $parent_row = $this->model->where('id',$row->pid)->find();
                if ($parent_row){
                    $parent_row->get_hours=$parent_row->get_hours+$row->get_hours;
                    $row->project->task_count--;
                    $parent_row->save();
                }

            }else{
                //项目任务数量-1
                $row->project->task_count--;
                //减去项目安排工时
                $row->project->task_hours= $row->project->task_hours-$row->get_hours;

            }
            $row->project->save();
            //删除附件
            \app\admin\model\workteam\Files::where('task_id',$row->id)->delete();
            $row->delete();

            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();

    }

	protected function getMonthDays(){
		$days = [];
		for($i=1;$i<=31;$i++){
			$days[$i] = $i;
		}
		return $days;
	}
}
